var Trip = { Departure: null, Arrival: null, Walk: 0.21, Minimize: 'transfers', Use: 'both' };

Wheels.TripPlanner = new Ext.form.FormPanel({
    scroll: 'vertical',
    items: [
    {
        xtype: 'fieldset',
        title: 'Depart from:',
        instructions: '<div class="helpcommands"><img src="Application/resources/img/locate.png" onclick="setCurrentLocation(\'departure\')"><img src="Application/resources/img/maps.png" onclick="showDeparture()"><div>',
        items: [ { xtype: 'searchfield', name: 'departFrom', placeholder: 'Enter address or point location on the map.', value: '2000 s eads arlington' } ]
    },
    {
        xtype: 'fieldset',
        title: 'Arrive to:',
        instructions: '<div class="helpcommands"><img src="Application/resources/img/locate.png" onclick="setCurrentLocation(\'arrival\')"><img src="Application/resources/img/maps.png" onclick="showArrival()"><div>',
        items: [ { xtype: 'searchfield', name: 'arriveTo', placeholder: 'Enter address or point location on the map.', value: '3307 M St NW, Washington, DC 20007'} ]
    },
    { xtype: 'button', text: 'Preferences', handler: function () { setCard('trip-planner-advanced'); } },
    new Ext.Button({ text: 'Plan', style: 'margin-top: 20px', handler: function () { planTrip(); setCard('trip-planner-results'); } })
    ]
});

var geocoder = new google.maps.Geocoder();
var pinAllowed = false;
function showMap(mode) {
    //HACK: Was unable to assign listener on any map initialization events (map object isn't available at that time), so decided to do it here.

    var isAvailable = mapContainer.map;
    setCard('trip-planner-map');
    currentMode = mode;

    if (!isAvailable) {

        google.maps.event.addListener(mapContainer.map, 'dragstart', hideActiveMenu);
        google.maps.event.addListener(mapContainer.map, 'dragstart', hideActiveMenu);
        google.maps.event.addListener(mapContainer.map, 'dragend', showStopsForBounds);
        //google.maps.event.addListener(mapContainer.map, 'zoom_changed', function () { activeMenu.hide() });

        google.maps.event.addListener(mapContainer.map, 'click', function (event) { dropPin(event.latLng); });
        //google.maps.event.addDomListener(mapContainer.map.C.d, "mousedown", function () { });
    }
}

function dispatchClick(control, x, y) {
    var evt = document.createEvent("MouseEvents");

    evt.initMouseEvent("click", true, true, window, 0, 0, 0, x, y, false, false, false, false, 0, null);
    //event.initMouseEvent(type, canBubble, cancelable, view, detail, screenX, screenY, clientX, clientY, ctrlKey, altKey, shiftKey, metaKey, button, relatedTarget);
    var canceled = !control.dispatchEvent(evt);

    //if (canceled) { alert("canceled"); } else { alert("not canceled"); }
}

function showDeparture() {
    Wheels.TripPlanner.updateModel(TripPlan, true);
    var address = TripPlan.data.departFrom;
    getLocationByAddress(address, function (location, formattedAddress) {
        if (location) { updateDeparture(formattedAddress); }
        showMap('trip-planning');
        updateMarkerFrom(location);
    });
}

function showArrival() {
    Wheels.TripPlanner.updateModel(TripPlan, true);
    var address = TripPlan.data.arriveTo;
    getLocationByAddress(address, function (location, formattedAddress) {
        if (location) { updateArrival(formattedAddress); }
        showMap('trip-planning');
        updateMarkerTo(location);
    });
}


function updateDeparture(value) {
    Wheels.TripPlanner.updateModel(TripPlan, true);
    TripPlan.data.departFrom = value;
    Wheels.TripPlanner.loadModel(TripPlan);
}

function updateArrival(value) {
    Wheels.TripPlanner.updateModel(TripPlan, true);
    TripPlan.data.arriveTo = value;
    Wheels.TripPlanner.loadModel(TripPlan);
}

function getLocationByAddress(address, resultHandler) {
    geocoder.geocode({ address: address }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var location = results[0].geometry.location;
            resultHandler(location, results[0].formatted_address);
        }
        else { resultHandler(null, null) }
    });
}

function getAddressByLatLng(latLng, resultHandler) {
    geocoder.geocode({ latLng: latLng }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            resultHandler(results[0].formatted_address);
        }
        else { resultHandler(latLng.toString()); }
    });
}

function planTrip() {
    Wheels.TripPlanner.updateModel(TripPlan, true);
    var departFromAddress = TripPlan.data.departFrom;
    var arriveToAddress = TripPlan.data.arriveTo;

    geocoder.geocode({ address: departFromAddress }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var location = results[0].geometry.location;
            var formattedAddress = results[0].formatted_address;

            updateDeparture(formattedAddress);
            Trip.Departure = { Lat: location.lat(), Lng: location.lng() };
        }
    });

    geocoder.geocode({ address: arriveToAddress }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var location = results[0].geometry.location;
            var formattedAddress = results[0].formatted_address;

            updateArrival(formattedAddress);
            Trip.Arrival = { Lat: location.lat(), Lng: location.lng() };
        }
    });

    var interval = setInterval(function () {
        if (Trip.Departure && Trip.Arrival) {
            clearInterval(interval);
            getResults();
        }
    })
}
